package org.jeecg.modules.online.cgform.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.online.cgform.converter.ConvertUtil;
import org.jeecg.modules.online.cgform.entity.OnlCgformField;
import org.jeecg.modules.online.cgform.entity.OnlCgformHead;
import org.jeecg.modules.online.cgform.mapper.OnlCgformFieldMapper;
import org.jeecg.modules.online.cgform.service.IOnlCgformFieldService;
import org.jeecg.modules.online.cgform.service.IOnlCgformHeadService;
import org.jeecg.modules.online.cgform.service.IOnlCgformSqlService;
import org.jeecg.modules.online.cgform.util.CgformUtil;
import org.jeecg.modules.online.config.exception.BusinessException;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * @Description: Online表单开发
 * @Author: jeecg-boot
 * @Date:   2019-03-12
 * @Version: V1.0
 */
@Service("onlCgformSqlServiceImpl")
public class OnlCgformSqlServiceImpl implements IOnlCgformSqlService {

	@Autowired
    private SqlSessionTemplate sqlSessionTemplate;

	@Autowired
	private IOnlCgformHeadService onlCgformHeadService;

	@Override
	public void saveBatchOnlineTable(OnlCgformHead head, List<OnlCgformField> fieldList, List<Map<String, Object>> dataList) {
        SqlSession batchSqlSession = null;
        try {
        	ConvertUtil.doConvertDataList(ConvertUtil.in,dataList,fieldList);
			// 获取批量方式的sqlsession
            batchSqlSession = this.sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
            //通过新的session获取mapper
            OnlCgformFieldMapper mapper = batchSqlSession.getMapper(OnlCgformFieldMapper.class);
			// 每批commit的个数
            int batchCount = 1000;
            
            if(batchCount>=dataList.size()) {
            	for (int index = 0; index < dataList.size();index++) {
            		String jsonStr = JSON.toJSONString(dataList.get(index));
					saveOrUpdateOneData(jsonStr,head,fieldList,mapper);
            	}
            }else {
            	for (int index = 0; index < dataList.size();index++) {
            		String jsonStr = JSON.toJSONString(dataList.get(index));
					saveOrUpdateOneData(jsonStr,head,fieldList,mapper);
                	if(index%batchCount==0) {
                		batchSqlSession.commit();
                        //清理缓存，防止溢出
                        batchSqlSession.clearCache();
                		
                	}
            	}
            }
            batchSqlSession.commit();
        } catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            batchSqlSession.close();
        }
		
	}

	@Override
	public void saveOrUpdateSubData(String subDataJsonStr, OnlCgformHead head, List<OnlCgformField> subFiledList) throws BusinessException {
		OnlCgformFieldMapper mapper = SpringContextUtils.getBean(OnlCgformFieldMapper.class);
		saveOrUpdateOneData(subDataJsonStr,head,subFiledList,mapper);
	}

	/**
	 * 导入时 通过增强判断是否需要修改 或者 丢弃此数据
	 * @param dataJsonStr 表单数据JSON 字符串
	 * @param head 表配置
	 * @param fieldList 表字段配置
	 * @param mapper
	 */
	private void saveOrUpdateOneData(String dataJsonStr,OnlCgformHead head,List<OnlCgformField> fieldList,OnlCgformFieldMapper mapper) throws BusinessException {
		JSONObject importData = JSONObject.parseObject(dataJsonStr);
		int flag = onlCgformHeadService.executeEnhanceJava(CgformUtil.ENHANCE_IMPORT,CgformUtil.ENHANCE_TYPE_START,head,importData);
		String tableName = head.getTableName();
		if(CgformUtil.OL_IMPORT_INSERT == flag){
			//新增数据
			Map<String,Object> map = CgformUtil.getFormDataSaveSql(tableName, fieldList, importData);
			mapper.executeInsertSQL(map);
		}else if(CgformUtil.OL_IMPORT_UPDATE == flag){
			//修改数据
			Map<String,Object> map = CgformUtil.getFormDataEditSql(tableName, fieldList, importData);
			mapper.executeUpdatetSQL(map);
		}else if(CgformUtil.OL_IMPORT_ABD == flag){
			// 丢弃此数据
		}
	}

}
